<template>
  <div>
    <div v-if="loading" style="text-align: center;padding: 50px;">
      <a-spin></a-spin>
    </div>
    <entity-view v-else @submit="submit" ref="baseForm" :model="beanInfo" :rules="rules" :operator-type="operatorType">
      <form-item label="商户类型" v-model="beanInfo.mchntType" prop="mchntType" input-type="select" :disabled="operatorType !== 'add'" :options="[
      {value: '00', name: '普通商户'},
      {value: '20', name: '小微商户'},
      {value: '10', name: '连锁商户'},
      {value: '11', name: '连锁商户门店'},
    ]" @change="merchantTypeChange"></form-item>
      <form-item label="商户等级" v-model="beanInfo.mchntLevel" prop="mchntLevel" input-type="select" :options="merchantLevel" show-search :fetching="inputFetching" @search="getMerchantLevels"></form-item>
      <form-item label="商户号" v-model="beanInfo.mchntNo" prop="mchntNo" disabled></form-item>
      <form-item label="商户名称" v-model="beanInfo.mchntName" prop="mchntName" :max-length="64"></form-item>
      <form-item label="商户简称" v-model="beanInfo.mchntSimpleName" prop="mchntSimpleName" :max-length="64"></form-item>
      <form-item label="主体性质" v-model="beanInfo.mchntNature" prop="mchntNature" input-type="select" :options="merchantNature" :disabled="operatorType !== 'add'"></form-item>
      <form-item label="商户类别组别" v-model="beanInfo.managementScope" prop="managementScope" input-type="select" :disabled="beanInfo.auditStatus!=='00'&&beanInfo.auditStatus!=='03'" :options="merchantTypeGroup" show-search :fetching="inputFetching" @search="getMerchantTypeGroups"></form-item>
      <form-item label="商户类别代码" v-model="beanInfo.industryType" prop="industryType" input-type="select" :disabled="beanInfo.auditStatus!=='00'&&beanInfo.auditStatus!=='03'" :options="merchantType" show-search :fetching="inputFetching" @search="getMerchantTypes"></form-item>
      <!-- todo: 下拉框数据接口不可用，待添加下拉框数据 -->
      <form-item label="签约机构" v-model="beanInfo.signInstId" prop="signInstId" disabled></form-item>

      <form-item label="是否独立维护商户资料" v-if="beanInfo.mchntType === '11'" v-model="beanInfo.independentDataFlag"
                 prop="independentDataFlag" input-type="radioGroup" :options="[ {value: 'Y', label: '是'},
        {value: 'N', label: '否'}]" :disabled="operatorType !== 'add'"></form-item>

      <form-item label="连锁商户号" v-if="beanInfo.mchntType === '11'" v-model="beanInfo.chainMchntNo" :options="chainMerchantNo" prop="chainMchntNo" input-type="select" show-search :fetching="inputFetching" @search="getChainMerchantNo" :max-length="15" :disabled="operatorType !== 'add'"></form-item>
      <form-item label="所属平台商户" v-model="beanInfo.platMchntNo" prop="platMchntNo" input-type="select" :options="platformMerchant" show-search :fetching="inputFetching" @search="getPlatformMerchant"></form-item>
      <form-item label="所属集团商户" v-model="beanInfo.groupMchntNo" prop="groupMchntNo" input-type="select" :options="groupMerchant" show-search :fetching="inputFetching" @search="getGroupMerchant"></form-item>
      <form-item label="所属商圈" v-model="beanInfo.mchntArea" prop="mchntArea" input-type="select" :options="merchantArea" show-search :fetching="inputFetching" @search="getMerchantArea"></form-item>
      <form-item label="是否支持自助开展营销活动" v-if="pageInfo.marketFlag" v-model="beanInfo.marketFlag" prop="marketFlag" input-type="radioGroup" ::options="[ {value: 'Y', label: '是'},
        {value: 'N', label: '否'}]" ></form-item>
      <form-item label="商户营业面积(平方米)" v-model="beanInfo.mchntBizArea" prop="mchntBizArea" :max-length="18"></form-item>
      <form-item label="员工人数" v-model="beanInfo.employeeNum" prop="employeeNum" :max-length="6"></form-item>
      <form-item label="营业开始时间" v-model="beanInfo.bizStartTime" prop="bizStartTime" input-type="datepicker" mode="time" date-format="HH:mm:ss"></form-item>
      <form-item label="营业结束时间" v-model="beanInfo.bizEndTime" prop="bizEndTime" input-type="datepicker" mode="time" date-format="HH:mm:ss"></form-item>
      <form-item label="营业地址" v-model="beanInfo.mchntAddress" prop="mchntAddress" input-type="cascader" :options="address" :load-data="getAddress"></form-item>
      <form-item label="营业详细地址" type="textArea" v-model="beanInfo.mchntBizAddr" prop="mchntBizAddr"></form-item>

      <form-item label="商户经度坐标" v-model="beanInfo.mchntLng" prop="mchntLng" :max-length="18"></form-item>

      <form-item label="商户纬度坐标" v-model="beanInfo.mchntLat" prop="mchntLat" :max-length="18"></form-item>

      <a-col span="12" v-if="pageInfo.AGENTMCHNTNO === 'Y'">
        <a-form-item label="所属代理机构" :labelCol="{span: 10}">
          <pagination-search-select v-model="beanInfo.agentMchntNo" :listUrl="getAgentMchntListUrl"
                                    :listUrlParam="agentMchntNoListUrlParam"
                                    valueName="id" :showNameArr="showNameArr"
                                    :pageSize="10" :openSearch="true" :searchWordKeyArr="searchWordKey":disabled="operatorType !== 'add' && operatorType !== 'edit'">
          </pagination-search-select>
        </a-form-item>
      </a-col>


      <form-item label="商户联系人" v-model="beanInfo.mchntContactName" prop="mchntContactName" :max-length="16"></form-item>
      <form-item label="商户联系人证件类型" v-model="beanInfo.mchntContactCertType" prop="mchntContactCertType"  @change="contactCertTypeChange" input-type="select" :options="[
      {value: '99', name: '其它'},
      {value: '01', name: '身份证'},
      {value: '02', name: '军官证'},
      {value: '03', name: '护照'},
      {value: '04', name: '户口薄'},
      {value: '05', name: '士兵证'},
      {value: '06', name: '港澳来往内地通行证'},
      {value: '07', name: '台湾同胞来往内地通行证'},
      {value: '08', name: '临时身份证'},
      {value: '09', name: '外国人居留证'},
      {value: '10', name: '警官证'},
    ]"></form-item>
      <form-item label="商户联系人证件号码" v-model="beanInfo.mchntContactCertNo" prop="mchntContactCertNo"  @click.native="setContactCertNo"></form-item>
      <form-item label="证件生效日期" v-model="beanInfo.certEffectiveDate" prop="certEffectiveDate" input-type="datepicker" date-format="YYYY-MM-DD"></form-item>
      <form-item label="证件失效日期" v-model="beanInfo.certExpiryDate" prop="certExpiryDate">
        <a-date-picker  allow-clear :disabled="operatorType !== 'add' && operatorType !== 'edit'"  date-format="YYYY-MM-DD">
          <a-input v-if="beanInfo.certExpiryDate === '长期'" allow-clear v-model="beanInfo.certExpiryDate" ></a-input>
        </a-date-picker>
        <a href="javascript:" @click="setLongTime('certExpiryDate')" v-if="operatorType === 'add' || operatorType === 'edit'" style="margin-left: 10px">长期</a>
      </form-item>
      <form-item label="商户联系电话" v-model="beanInfo.mchntContactPhone" prop="mchntContactPhone" :max-length="20"></form-item>
      <form-item label="商户联系人手机号" v-model="beanInfo.mchntContactMobile" prop="mchntContactMobile" :max-length="20"></form-item>
      <form-item label="商户联系人邮箱" v-model="beanInfo.mchntContactEmail" prop="mchntContactEmail" :max-length="64"></form-item>
      <form-item label="商户属性" v-model="beanInfo.mchntAttr" prop="mchntAttr" input-type="select" :options="[
      {value: '01', name: '实体特约商户'},
      {value: '10', name: '网络特约商户'},
      {value: '11', name: '实体兼网络特约商户'},
    ]"></form-item>
      <form-item v-if="beanInfo.mchntAttr !== '01'" label="网络域名" v-model="beanInfo.mchntNetworkDomain" prop="mchntNetworkDomain" :max-length="128"></form-item>
      <form-item v-if="beanInfo.mchntAttr !== '01'" label="ICP备案号" v-model="beanInfo.icpRecordNo" prop="icpRecordNo" :max-length="32"></form-item>
      <form-item v-if="beanInfo.mchntAttr !== '01'" label="IP地址" v-model="beanInfo.ip" prop="ip" :max-length="32"></form-item>
      <form-item v-if="beanInfo.mchntAttr !== '01'" label="商户签约类型" v-model="beanInfo.mchntSignType" prop="mchntSignType" input-type="select" :options="mchntSignType"></form-item>

      <!-- 原系统是隐藏状态 -->
      <form-item label="是否支持小额免密" v-if="false" v-model="beanInfo.noPasswordFlag" prop="noPasswordFlag" input-type="radio"></form-item>

      <!--  TODO：待添加正则校验  -->
      <form-item label="小额免密金额" v-if="!beanInfo.noPasswordFlag === 'N'" v-model="beanInfo.noPasswordAmt" prop="noPasswordAmt"></form-item>
      <form-item label="拓展经理工号" v-model="beanInfo.managerId" prop="managerId" input-type="select" :options="manager" show-search :fetching="inputFetching" @search="getManager" @change="managerChange"></form-item>
      <form-item label="拓展经理姓名" v-model="beanInfo.managerName" prop="managerName" disabled></form-item>
      <div class="btn-wrapper">
        <a-button type="primary" html-type="submit" class="btn-next">下一步</a-button>
      </div>
    </entity-view>
  </div>
</template>

<script>
import EntityView from '../../../../components/common/entityView/EntityView.vue'
import FormItem from '../../../../components/common/entityView/FormItem.vue'
import moment from 'moment';
import debounce from 'lodash/debounce'
import PaginationSearchSelect from '@/components/select/PaginationSearchSelect'

const selectData = {
  merchantNature: [
    {value: '01', name: '小微商户'},
    {value: '02', name: '个体工商户'},
    {value: '03', name: '企业'},
    {value: '04', name: '党政机关及事业单位'},
    {value: '99', name: '其他组织'},
  ]
}

export default {
  name: 'BaseInfoForm',
  components: {EntityView, FormItem,PaginationSearchSelect},
  inject: ['merchantBaseInfoContext', 'operationContext'],
  watch: {
    'operationContext.modalVisible': function (val) {
      if (val) {
        this.getPageInfo()
      }
    }
  },
  data: function () {
    this.lastFetchId = 0;
    this.getMerchantLevels = debounce(this.getMerchantLevels, 500);

    this.getMerchantTypeGroups = debounce(this.getMerchantTypeGroups, 500);

    this.getMerchantTypes = debounce(this.getMerchantTypes, 500);

    this.getPlatformMerchant = debounce(this.getPlatformMerchant, 500)

    this.getGroupMerchant = debounce(this.getGroupMerchant, 500)

    this.getMerchantArea = debounce(this.getMerchantArea, 500)

    this.getManager = debounce(this.getManager, 500)

    return {
      pageInfo: {
        marketFlag: "", // 是否显示“是否支持自助开展营销活动”
        AGENTMCHNTNO: "", // 所属代理机构
        SMSSENDFLAG: "", // 是否发送短信通知
        registerProvinceName: "", // 注册省份
        mchntArea: "", // 所属商圈
      },
      beanInfo: {
        mchntType: '',
        mchntAddress:[]
      },
      rules: {
        mchntType: [{required: true, message: '请选择商户类型', trigger: 'blur'}],
        mchntLevel: [{required: true, message: '请选择商户等级', trigger: 'blur'}],
        mchntNo: [{required: true, message: '商户号不能为空', trigger: 'blur'}],
        mchntName: [{required: true, message: '请输入商户名称', trigger: 'blur'}],
        mchntSimpleName: [{required: true, message: '请输入商户简称', trigger: 'blur'}],
        mchntNature: [{required: true, message: '请选择主体性质', trigger: 'blur'}],
        managementScope: [{required: true, message: '请选择商户类别组别', trigger: 'blur'}],
        industryType: [{required: true, message: '请选择商户类别代码', trigger: 'blur'}],
        chainMchntNo: [{required: true, message: '请选择连锁商户号', trigger: 'blur'}],
        signInstId: [{required: true, message: '请选择签约机构', trigger: 'blur'}],
        mchntBizArea: [{
          validator(rule, value, callback) {
            callback(value ? (/^[0-9]+(.[0-9]{1,2})?$/.test(value) ? undefined : new Error('请输入正确的格式')) : undefined)
          },
          trigger: 'blur'
        }],
        employeeNum: [{
          validator(rule, value, callback) {
            callback(value ? (/^\d+$/.test(value) ? undefined : new Error('请输入正确的格式')) : undefined)
          },
          trigger: 'blur'
        }],
        mchntAddress: [{required: true,
          validator(rule, value, callback) {
            callback(value ? (value.length === 3 ? undefined : new Error('请输入正确的格式')) : new Error('请选择营业地址'))
          },
          trigger: 'blur'
        }],
        mchntBizAddr: [{required: true, message: '请输入营业详细地址', trigger: 'blur'}],
        mchntLng: [{
          validator(rule, value, callback) {
            callback(value ? (/^\d+\.\d+$/.test(value) ? undefined : new Error('请输入正确的格式')) : undefined)
          },
          trigger: 'blur'
        }],
        mchntLat: [{
          validator(rule, value, callback) {
            callback(value ? (/^\d+\.\d+$/.test(value) ? undefined : new Error('请输入正确的格式')) : undefined)
          },
          trigger: 'blur'
        }],
        mchntContactName: [{required: true, message: '请输入商户联系人', trigger: 'blur'}],

        mchntContactPhone: [{required: true, message: '请输入联系电话', trigger: 'blur'},{
          validator(rule, value, callback) {
            callback(value ? (/^[0][0-9]{2,3}-[0-9]{5,10}$/.test(value) ? undefined : new Error('请输入正确的格式')) : undefined)
          },
          trigger: 'blur'
        }],
        mchntContactMobile: [{required: true, message: '请输入联系人手机号', trigger: 'blur'}, {
          validator(rule, value, callback) {
            callback(value ? (/^[1][3,4,5,7,8][0-9]{9}$/.test(value) ? undefined : new Error('请输入正确的格式')) : undefined)
          },
          trigger: 'blur'
        }],
        mchntContactEmail: [{
          validator(rule, value, callback) {
            callback(value ? (/^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/.test(value) ? undefined : new Error('请输入正确的格式')) : undefined)
          },
          trigger: 'blur'
        }],
        mchntAttr: [{required: true, message: '请选择商户属性', trigger: 'blur'}],
        mchntNetworkDomain: [{required: true, message: '请输入网络域名', trigger: 'blur'}],
        icpRecordNo: [{required: true, message: '请输入ICP备案号', trigger: 'blur'}],
        ip: [{required: true, message: '请输入IP地址', trigger: 'blur'}],
        managerId: [{required: true, message: '请选择拓展经理工号', trigger: 'blur'}],
        managerName: [{required: true, message: '拓展经理姓名不能为空', trigger: 'blur'}],
      },
      loading: false,
      inputFetching: false,
      merchantLevel: [], // 商户等级下拉框数据
      merchantTypeGroup: [], // 商户组别下拉框数据
      merchantType: [], // 商户类别下拉框数据
      chainMerchantNo: [], // 连锁商户号下拉框数据
      platformMerchant: [], // 平台商户下拉框数据
      groupMerchant: [], // 集团商户下拉框数据
      merchantArea: [], // 商圈下拉框数据
      manager: [], // 拓展经理下拉框数据
      searchWordKey:['agentMchntNo'],
      showNameArr:['id','name'],
      getAgentMchntListUrl:'/admin/mcmp/bMchntBaseInfo/agentMchntSelect2List',
      agentMchntNoListUrlParam: {'instId': this.merchantBaseInfoContext.query.instId},

      address: [],

      merchantNature: selectData.merchantNature,
      optFlag:"",
      operatorType:"add",

    }
  },
  computed: {
    mchntSignType () {
      return this.beanInfo.platMchntNo ? [
        {value: '00', name: '银行级签约'},
        {value: '01', name: '平台级签约'},
        {value: '02', name: '商户级签约'},
      ] : [
        {value: '00', name: '银行级签约'},
        {value: '02', name: '商户级签约'},
      ]
    }
  },
  mounted () {
    this.getPageInfo()
    this.getAddress()
  },
  methods: {
    contactCertTypeChange (val) {
      this.beanInfo.mchntContactCertType = val;
      if (val === '01') {
        this.$set(this.rules, 'mchntContactCertNo', [{required: false, message: '请输入联系人证件号码', trigger: 'blur'}, {
          validator(rule, value, callback) {
            callback(value ? (/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value) ? undefined : new Error('请输入正确的身份证格式')) : undefined)
          },
          trigger: 'blur'
        }])
      } else {
        this.$set(this.rules, 'mchntContactCertNo', [{required: false, message: '请输入联系人证件号码', trigger: 'blur'}, {
          validator(rule, value, callback) {
            callback(value ? (/^[a-zA-Z1-9][a-zA-Z0-9]{0,30}$/.test(value) ? undefined : new Error('请输入正确的证件格式')) : undefined)
          },
          trigger: 'blur'
        }])
      }
    },

    setContactCertNo(){
      if(typeof this.beanInfo.mchntContactCertType === 'undefined' || this.beanInfo.mchntContactCertType === ''){
        this.warning('请先选择法人证件类型')
      }
    },
    warning(message){
      const h = this.$createElement;
      this.$warning({
        title: '提示',
        content: h('div', {}, [
          h('p', message),
        ]),
        onOk() {},
      });
    },
    async submit () {
      try {
        if(this.operatorType === 'edit' || this.operatorType === 'add'){
          const res = await this.$refs.baseForm.validate()
          if (res) {
            const params = Object.assign({}, this.beanInfo)
            if (params.mchntAddress) {
              params.mchntBizProvince = params.mchntAddress[0]
              params.mchntBizCity = params.mchntAddress[1]
              params.mchntBizRegion = params.mchntAddress[2]
            }
            if (params.bizStartTime) {
              params.bizStartTime = params.bizStartTime.format('HHmmss')
            }
            if (params.bizEndTime) {
              params.bizEndTime = params.bizEndTime.format('HHmmss')
            }
            if (params.certEffectiveDate) {
              params.certEffectiveDate = params.certEffectiveDate.format('YYYYMMDD')
            }
            if (params.certExpiryDate && params.certExpiryDate !== '长期') {
              params.certExpiryDate = params.certExpiryDate.format('YYYYMMDD')
            }
            const res = await this.$post('/admin/mcmp/bMchntBaseInfo/edit', params)

            if (res.status === 200) {
              if(res.data.respCode==='00000000'){
                this.$message.success('保存成功！')
                this.operationContext.beanInfo.mchntNo = res.data.mchntNo
                this.$emit("submit");
                return true
              } else {
                this.$message.error(res.data.respMsg)
                return false
              }
            } else {
              this.$message.error(res.data.respMsg)
              return false
            }
          }
        }else{
          this.$emit("submit");
        }
      } catch (e) {
        console.error(e)
      }
      return false
    },
    resetFields () {
      return this.$refs.form.resetFields()
    },
    async getPageInfo () {
      try {
        this.operatorType = this.operationContext.operatorType;
        let optFlag = {add: `add`, edit: `upd`, view: `view`, use: `use`, stop: `stop`, cancel: `cancel`, chk: `chk`}[this.operatorType]
        this.loading = true;
        const param = {
          optFlag: optFlag,
          instId: this.merchantBaseInfoContext.query.instId
        }
        if(optFlag !== 'add'){
          param.mchntNo = this.operationContext.beanInfo.mchntNo
        }
        const res = await this.$get('/admin/mcmp/bMchntBaseInfo/edit',param )
        this.loading = false;
        this.beanInfo = res.data.entity
        this.pageInfo = res.data
        this.operationContext.flag = (res.data.entity.mchntType === '11'&&res.data.entity.independentDataFlag === 'N')?'N':'Y'
        if(optFlag !== 'add'){
          this.contactCertTypeChange(this.beanInfo.mchntContactCertType)
          this.beanInfo.mchntAddress = []
          this.beanInfo.mchntAddress.push(this.beanInfo.mchntBizProvince)
          this.beanInfo.mchntAddress.push(this.beanInfo.mchntBizCity)
          this.beanInfo.mchntAddress.push(this.beanInfo.mchntBizRegion)
          if (this.beanInfo.bizStartTime) {
            this.beanInfo.bizStartTime = moment(this.beanInfo.bizStartTime,'HH:mm:ss')
          }
          if (this.beanInfo.bizEndTime) {
            this.beanInfo.bizEndTime = moment(this.beanInfo.bizEndTime,'HH:mm:ss')
          }
          if (this.beanInfo.certEffectiveDate) {
            this.beanInfo.certEffectiveDate = moment(this.beanInfo.certEffectiveDate,'YYYY-MM-DD')
          }
          if (this.beanInfo.certExpiryDate && this.beanInfo.certExpiryDate !== '长期') {
            this.beanInfo.certExpiryDate = moment(this.beanInfo.certExpiryDate,'YYYY-MM-DD')
          }
          await this.getMerchantLevels()
          await this.getMerchantTypeGroups()
          await this.getMerchantTypes()
          await this.getChainMerchantNo()
          await this.getPlatformMerchant()
          await this.getGroupMerchant()
          await this.getMerchantArea()
          await this.getManager()
        }
      } catch (e) {
        console.error(e)
        this.loading = false;
      }
    },
    /**
     *
     * @param value {String}
     * @param url {String}
     * @param params {Object}
     * @return {Promise<void>}
     */
    async debounceSearch({value, url, params}) {

      try {
        this.inputFetching = true
        const res = await this.$get(url, params)
        this.inputFetching = false
        if (res.status === 200) {
          return res
        }
      } catch (e) {
        this.inputFetching = false
        console.error(e)
      }
    },
    async getMerchantLevels (value = '') {
      this.merchantLevel = [];
      const res = await this.debounceSearch({
        value,
        url: '/admin/mcmp/bMchntBaseInfo/mchntLevelSelect2List',
        params: {q: encodeURIComponent(value + '&' + this.merchantBaseInfoContext.query.instId)},
      })
      this.merchantLevel = res.data.results.map(i => {
        i.name = i.id + ' - ' + i.name
        i.value = i.id
        return i
      })
    },
    async getMerchantTypeGroups (value = '') {
      this.merchantTypeGroup = [];
      const res = await this.debounceSearch({
        value,
        url: '/admin/mcmp/bMchntBaseInfo/unionMerGrpSelect2List',
        params: {q: encodeURIComponent(value + '&' + this.merchantBaseInfoContext.query.instId)},
      })
      this.merchantTypeGroup = res.data.rows.map(i => {
        i.name = i.grpNo + ' - ' + i.grpDesc
        i.value = i.grpNo
        return i
      })
    },
    async getMerchantTypes (value = '') {
      if (!this.beanInfo.managementScope){
        this.$message.error("请先选择商户组别")
        return
      }
      this.merchantType = [];
      const res = await this.debounceSearch({
        value,
        url: '/admin/mcmp/bMchntBaseInfo/industryTypeSelect2List',
        params: {q: encodeURIComponent(value + '&' + this.merchantBaseInfoContext.query.instId + '&' + this.beanInfo.managementScope)},
      })
      this.merchantType = res.data.results.map(i => {
        i.name = i.id + ' - ' + i.name
        i.value = i.id
        return i
      })
    },
    async getChainMerchantNo (value = '') {
      this.chainMerchantNo = [];
      const res = await this.debounceSearch({
        value,
        url: '/admin/mcmp/bMchntBaseInfo/chainMchntNo',
        params: {q: encodeURIComponent(value + '&' + this.merchantBaseInfoContext.query.instId + '&' + this.beanInfo.signInstId)},
      })
      this.chainMerchantNo = res.data.rows.map(i => {
        i.name = i.mchntNo + ' - ' + i.mchntName
        i.value = i.mchntNo
        return i
      })
    },
    async getPlatformMerchant (value = '') {
      this.platformMerchant = [];
      const res = await this.debounceSearch({
        value,
        url: '/admin/mcmp/bMchntBaseInfo/platMchntSelect2List',
        params: {q: encodeURIComponent(value + '&' + this.merchantBaseInfoContext.query.instId)},
      })
      this.platformMerchant = res.data.results.map(i => {
        i.name = i.id + ' - ' + i.name
        i.value = i.id
        return i
      })
    },
    async getGroupMerchant (value = '') {
      this.groupMerchant = [];
      const res = await this.debounceSearch({
        value,
        url: '/admin/mcmp/bMchntBaseInfo/groupMchntSelect2List',
        params: {q: encodeURIComponent(value + '&' + this.merchantBaseInfoContext.query.instId)},
      })
      this.groupMerchant = res.data.results.map(i => {
        i.name = i.grpNo + ' - ' + i.grpDesc
        i.value = i.grpNo
        return i
      })
    },
    async getMerchantArea (value = '') {
      this.merchantArea = [];
      const res = await this.debounceSearch({
        value,
        url: '/admin/mcmp/bMchntBaseInfo/mchntAreaSelect2List',
        params: {q: encodeURIComponent(value + '&' + this.merchantBaseInfoContext.query.instId + '&' + this.beanInfo.signInstId)},
      })
      this.merchantArea = ((res.data && res.data.results) || []).map(i => {
        i.name = i.id + ' - ' + i.name
        i.value = i.id
        return i
      })
    },
    async getManager (value = '') {
      let signInstId = ''
      let signInstType = ''
      if (this.beanInfo.agentMchntNo && this.pageInfo.AGENTMCHNTNO === 'Y') {
        signInstId = this.beanInfo.agentMchntNo
        signInstType = 'AGENT'
      } else {
        signInstId = this.beanInfo.signInstId
        signInstType = 'BANK'
      }
      this.manager = [];
      const res = await this.debounceSearch({
        value,
        url: '/admin/mcmp/bMchntBaseInfo/managerInfoSelect2List',
        params: {q: encodeURIComponent(`${value}&${this.merchantBaseInfoContext.query.instId}&${signInstType}&${signInstId}&40`)},
      })
      this.manager = ((res.data && res.data.results) || []).map(i => {
        i.name = i.id + ' - ' + i.name
        i.value = i.id
        return i
      })
    },

    async getAddress (selectedOptions) {
      let targetOption
      if (selectedOptions) {
        targetOption = selectedOptions[selectedOptions.length - 1];
        targetOption.loading = true;
      }

      const res = await this.$get('/admin/mcmp/bMchntBaseInfo/registerselect2', {
        q: encodeURIComponent(`&${this.merchantBaseInfoContext.query.instId}&${(targetOption && targetOption.nextLevel || '01')}&${targetOption ? targetOption.id : ''}`),
        pageSize: 100,
        pageNum: 1,
      })

      targetOption && (targetOption.loading = false)
      const address = ((res.data && res.data.results) || []).map(i => {
        i.label = i.name;
        i.value = i.id;
        i.isLeaf = targetOption ? (targetOption.nextLevel === '03') : false // 是否是最后的节点
        i.nextLevel = targetOption ? '03' : '02'
        return i
      })
      if (targetOption) {
        targetOption.children = address
        this.address = [...this.address]
      } else {
        this.address = address
      }

    },

    setLongTime(field){
      this.$set(this.beanInfo, field, '长期')
    },

    managerChange (val) {
      this.$set(this.beanInfo, 'managerName', (this.manager.filter(i => {
        return i.id === val
      }))[0].name)
    },

    merchantTypeChange(val) {
      switch (val) {
        case '20':
          this.merchantNature = [{value: '01', name: '小微商户'},]
          this.beanInfo.mchntNature = '01'
          break
        default:
          this.merchantNature = selectData.merchantNature;
      }
    }
  },

}
</script>

<style scoped>
.btn-wrapper {
  padding: 0 10px;
  width: 100%;
  text-align: center;
}
</style>
